package com.young.shop.dao.impl;

import com.young.shop.dao.GoodsDao;
import com.young.shop.pojo.entity.Goods;
import com.young.shop.utils.DBManager;
import com.young.shop.utils.DBUtil;
import com.young.shop.utils.Utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class GoodsDaoimpl implements GoodsDao {

    //通过DBUtil类拿到queryRunner
    private QueryRunner queryRunner = DBUtil.getQueryRunner();

    @Override
    public List<Goods> servletGoodsAll() {
        String sql = "SELECT * FROM a_goods";
        Object[] params = {};

        //调用queryRunnerQuery方法向数据库查询,返回Goods对象集合,查不到为空
        return queryRunnerQuery(sql,params);

    }

    @Override
    public List<Goods> servletGoodsByName(String name) {
        String likeName = "%"+name+"%";
        String sql = "SELECT * FROM a_goods WHERE `goods_name` LIKE ?";
        Object[] params = {likeName};

        //调用queryRunnerQuery方法向数据库查询,返回Goods对象集合,查不到为空
        return queryRunnerQuery(sql,params);

    }

    @Override
    public Goods getGoodsById(String id) {
        String sql="select * from a_goods where id=?";
        Object[] params = {id};
        return queryRunnerQueryBean(sql,params);
    }




    //刘玥
   //通过id获取到产品的详细介绍
    @Override
    public Goods getIntroductionById(String id) {
        String sql="select * from a_goods where id=?";
        Goods goods = DBManager.selectOne(sql, Goods.class, id);
        return goods;
    }





    //抽离的queryRunnerQuery方法
    public List<Goods> queryRunnerQuery(String sql,Object[] params){
        //设置query返回的方式并开启驼峰映射
        BeanListHandler<Goods> beanListHandler = new BeanListHandler<>(Goods.class, Utils.getRowProcessor());

        try {
            List<Goods> goodsList = queryRunner.query(sql, beanListHandler, params);
            return goodsList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }

    }

    //抽离的queryRunnerQuery方法  返回查询到的单个数据的对象
    public Goods queryRunnerQueryBean(String sql,Object[] params){
        //设置query返回的方式并开启驼峰映射
        BeanHandler<Goods> beanHandler = new BeanHandler<>(Goods.class, Utils.getRowProcessor());

        try {
            Goods goods = queryRunner.query(sql, beanHandler, params);
            return goods;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }

    }


}
